<template>
  <div>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item
        prop="userName"
        label="用户名"
      >
        <el-input v-model="form.userName"></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import API from '@/api/rules'
export default {
  components: {},
  name: 'rules',
  data () {
    // 后台校验
    let validateUserName = (rule, value, callback) => {
      // 调用后台API校验用户名是否已存在
      API.validateUserNameApi(value).then(res => {
        if (res) {
          callback(new Error('账号已存在!'))
        } else {
          callback()
        }
      }).catch(() => {
        callback(new Error('账号验证重复api出错!'))
      })
    }
    return {
      form: {
        userName: ''
      },
      rules: {
        userName: [
          { required: true, min: 3, max: 20, message: '账户为3~20位', trigger: ['blur', 'change'] },
          { pattern: /^[A-Za-z0-9_]+$/, message: '由字母、数字、下划线组成', trigger: ['blur', 'change'] },
          { validator: validateUserName, trigger: 'blur' }
        ]
      }
    }
  }
}
</script>
